<?php
function copyPlainTextToClipboard(string $content = "") {
  $cmd =  "echo {$content}|" . (PHP_OS == "Darwin" ? "pbcopy" : (PHP_OS == "WINNT" ? "clip" : "xsel"));
  shell_exec($cmd);
}
function getPfx(string $certPath = "wx.p12", string $certPwd = "000000", bool $setClipboard = true) {
  if (!file_exists($certPath)) {
    echo "文件 [ {$certPath} ] 不存在.请注意相对稳健路径是相对于PHP文件的.";
    return;
  }
  $pkcs12certdata = file_get_contents($certPath);
  if ($pkcs12certdata === false) {
    echo ($certPath . "file_get_contents 函数失败。请检查文件");
    return;
  }

  if (openssl_pkcs12_read($pkcs12certdata, $certs, $certPwd) == false) {
    echo ($certPath . ", 证书密码[" . $certPwd . "] openssl_pkcs12_read 错误。");
    return;
  }

  $x509data = $certs["cert"];

  if (!openssl_x509_read($x509data)) {
    echo ($certPath . " openssl_x509_read 错误。请检查证书是否出了问题");
  }
  $certdata = openssl_x509_parse($x509data);
  $cert = array(
    "id" => $certdata["serialNumber"],
    "cert" => $x509data,
    "key" => $certs["pkey"]
  );
  // print_r($cert);
  $t = json_encode($cert, JSON_UNESCAPED_SLASHES); // PHP 5.4.0有效.否则会转码"/"为"\/"
  if ($setClipboard) {
    copyPlainTextToClipboard($t);
    echo $t . "\n\n// 已将数据放入剪切板,直接粘贴进配置文件中的private中即可";
  } else {
    echo $t;
  }
  return $t;
}
if (isset($argv)) {
  if ($argc < 3 || $argc > 4) {
    echo "用法: php -f index.php \"pfx文件绝对路径,或相对于index.php文件的相对路径\" pfx文件密码 [如果加入第三个参数,则只打印json数据,不将结果放入剪切板] ";
  } else {
    getPfx($argv[1], $argv[2], $argc == 4 ? false : true);
  }
} else {
  getPfx();
}
